package com.wenmang.networklib.frame;

import android.os.Handler;
import android.os.Looper;

import com.google.gson.Gson;
import com.wenmang.networklib.client.WMCallback;
import com.wenmang.networklib.utils.LogUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * desc:
 * 1.对方 IHttpListener 的扩展实现
 * 2.处理json 形式数据
 * <p>
 * author: created by zhoujx on 2018/10/19 15:01
 */
public class JSONHttpListener<M> implements IHttpListener {
    private static final String TAG = "JSONHttpListener";
    private Class<M> responseClass;
    private WMCallback callback;

    // 用于线程切换
    private Handler handler = new Handler(Looper.getMainLooper());

    public JSONHttpListener(Class<M> responseClass, WMCallback callback) {
        this.responseClass = responseClass;
        this.callback = callback;
    }

    @Override
    public void onSuccess(InputStream is) {
        // 获取响应结果把 InputStream 转换成 String
        String content = getContent(is);
        final M response = new Gson().fromJson(content, responseClass);

        handler.post(new Runnable() {
            @Override
            public void run() {
                if (null != callback) {
                    callback.onSuccess(response);
                }
            }
        });
    }

    @Override
    public void onFailure(final String errorMsg) {
        handler.post(new Runnable() {
            @Override
            public void run() {
                if (null != callback) {
                    callback.onFailure(errorMsg);
                }
            }
        });
    }

    private String getContent(InputStream is) {
        String content = null;
        try {
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is));
            StringBuilder stringBuilder = new StringBuilder();
            String line = null;
            try {
                while ((line = bufferedReader.readLine()) != null) {
                    stringBuilder.append(line + "\n");
                }
            } catch (IOException e) {
                LogUtils.e(TAG, e.getMessage());
            } finally {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            content = stringBuilder.toString();
        } catch (Exception e) {
            LogUtils.e(TAG, e.getMessage());
        }

        LogUtils.i(TAG, content);
        return content;
    }
}
